<template>
  <div class="map">
    <el-amap ref="map" :center="center" :zoom="zoom" @init="init" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, shallowRef } from "vue";
/** 地图实例    （shallowRef：如果有一个对象数据，后续功能不会修改该对象中的属性，而是生新的对象来替换） */
const myMap = shallowRef<typeof AMap | null>(null);
/** 地图中心点（默认） */
const center = reactive([121.59996, 31.197646]);
/** 地图缩放级别（默认） */
const zoom = ref(15);
const init = (map: typeof AMap ) => {
  // const AMap = (window as any).AMap;
  myMap.value = map;
  getUserPosition();
};
/** 添加地图标记点 */
const addMarker = () => {
  const marker = new AMap.Marker({
    position: [center[0],center[1]],
  });
  (myMap.value as any)?.add(marker);
};
/** 高德地图获取当前用户位置 */
const getUserPosition = () => {
  console.log("获取位置中...");
  AMap.plugin("AMap.Geolocation", function () {
    //异步加载插件
    const Geolocation = new (AMap as any).Geolocation({
      // 是否使用高精度定位，默认：true
      enableHighAccuracy: true,
      // 设置定位超时时间，默认：无穷大
      timeout: 6000,
      // 定位按钮的停靠位置的偏移量
      offset: [10, 20],
      //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
      zoomToAccuracy: true,
      //  定位按钮的排放位置,  RB表示右下
      position: "RB",
    });
    Geolocation.getCurrentPosition((status: any, result: any) => {
      if (status == "complete") {
        onComplete(result);
      } else {
        onError(result);
      }
    });
    function onComplete(res: any) {
      console.log(`获取位置成功:`, res);
      let { position } = res;
      center[0] = position.lng;
      center[1] = position.lat;
      addMarker();
      getAdd();
    }
    function onError(err: any) {
      console.log(`获取位置失败:`, err);
    }
  });
};
/** 地图加载完成后 （根据经纬度获取地址） */
const getAdd = () => {
  // const AMap = (window as any).AMap;
  const geocoder = new (AMap as any).Geocoder({
    radius: 1000,
    extensions: "all",
  });
  const [lng, lat] = center;
  geocoder.getAddress([lng, lat], function (status: any, result: any) {
    if (status === "complete" && result.info === "OK") {
      console.log(result, "result");
      if (result && result.regeocode) {
        console.log(
          `result.regeocode.formattedAddress:`,
          result.regeocode.formattedAddress
        );
      }
    }
  });
};
</script>

<style lang="scss" scoped>
.map {
  width: 100vw;
  height: 100vh;
}
</style>
